package org.rency.ues.engine.crypto.impl;

import org.rency.common.utils.security.X509CertUtils;
import org.rency.ues.common.UesDict;
import org.rency.ues.common.enums.EncryptType;
import org.rency.ues.domain.support.Certification;
import org.rency.ues.engine.crypto.Cryptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class RSACryptor implements Cryptor {
	
	private static final Logger logger = LoggerFactory.getLogger(RSACryptor.class);

    @Override
    public String getCryptorType() {
        return EncryptType.RSA.getCode();
    }

	@Override
	public String encrypt(byte[] plainData, Object... args) {
		if (args == null || args.length != 1) {
            logger.info("{}加密"+ UesDict.CHINESE_PARAMETER_INVALID_MSG,this.getCryptorType());
            return null;
        }
        try {
            if (args[0] instanceof Certification) {
                Certification certification = (Certification) args[0];
				return X509CertUtils.encryptRSA(plainData, certification.getCertificate());
            } else {
                logger.info("{}加密"+ UesDict.CHINESE_PARAMETER_INVALID_MSG,this.getCryptorType());
                return null;
            }
        } catch (Exception e) {
            logger.error("{}加密未知异常.",this.getCryptorType(),e);
            return null;
        }
	}

    @Override
	public byte[] decrypt(String enData, Object[] parameters) {
		if (parameters == null || parameters.length != 1) {
            logger.info("{}解密"+UesDict.CHINESE_PARAMETER_INVALID_MSG,this.getCryptorType());
            return null;
        }
        try {
            if (parameters[0] instanceof Certification) {
                Certification certification = (Certification) parameters[0];
				return X509CertUtils.decryptRSA(enData, certification.getPrivateKey());
            } else {
                logger.info("{}解密"+UesDict.CHINESE_PARAMETER_INVALID_MSG,this.getCryptorType());
                return null;
            }
        } catch (Exception e) {
            logger.error("{}解密未知异常.",this.getCryptorType(),e);
            return null;
        }
	}

}
